<?php

namespace app\admin\controller\shopro\lucky;

use addons\shopro\service\commission\Agent as AgentService;
use addons\shopro\service\Wallet as WalletService;
use app\admin\model\shopro\lucky\Order;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 预约报名
 *
 * @icon fa fa-circle-o
 */
class User extends Backend
{

    /**
     * User模型对象
     * @var \app\admin\model\shopro\lucky\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shopro\lucky\User;
        $this->view->assign("isLuckyList", $this->model->getIsLuckyList());
        $this->view->assign("stutasList", $this->model->getStutasList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['userinfo', 'server'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'commission', 'score', 'number', 'p_number', 'total_price', 'p_total_price', 'is_lucky', 'proportion', 'stutas', 'createtime']);
                $row->visible(['userinfo']);
                $row->getRelation('userinfo')->visible(['username', 'nickname', 'money', 'order_switch']);
                $row->visible(['server']);
                $row->getRelation('server')->visible(['name', 'open_lucky_time', 'createtime']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            if ($params['is_lucky'] == 1 && $params['proportion'] > 0) {

                \app\admin\model\shopro\lucky\Order::where(['status' => '0', 'lucky_user_id' => $ids])->orderRaw('rand()')->limit($params['proportion'])->update(['is_lucky' => 1]);

            } elseif ($params['is_lucky'] == 2) {

                \app\admin\model\shopro\lucky\Order::where(['status' => '0', 'lucky_user_id' => $ids])->update(['is_lucky' => 2]);

            } elseif ($params['is_lucky'] == 0) {
                \app\admin\model\shopro\lucky\Order::where(['status' => '0', 'lucky_user_id' => $ids])->update(['is_lucky' => 0]);

            }


            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function multi_check($ids = null)
    {
        $idsArr = explode(',', $ids);
        if (!$idsArr) {
            $this->error(__('未选中数据'));
        }
        $result = false;
        if (false === $this->request->isPost()) {
            $this->view->assign('row', []);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        Db::startTrans();
        try {
            foreach ($idsArr as $ids) {
                $row = $this->model->get($ids);
                if (!$row) {
                    Db::rollback();
                    $this->error(__('No Results were found'));
                }
                $adminIds = $this->getDataLimitAdminIds();
                if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
                    Db::rollback();
                    $this->error(__('You have no permission'));
                }
                $params = $this->preExcludeFields($params);

                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException()->validate($validate);
                }

                if ($params['is_lucky'] == 1 && $params['proportion'] > 0) {

                    \app\admin\model\shopro\lucky\Order::where(['status' => '0', 'lucky_user_id' => $ids])->orderRaw('rand()')->limit($params['proportion'])->update(['is_lucky' => 1]);

                } elseif ($params['is_lucky'] == 2) {

                    \app\admin\model\shopro\lucky\Order::where(['status' => '0', 'lucky_user_id' => $ids])->update(['is_lucky' => 2]);

                } elseif ($params['is_lucky'] == 0) {
                    \app\admin\model\shopro\lucky\Order::where(['status' => '0', 'lucky_user_id' => $ids])->update(['is_lucky' => 0]);

                }

                $result = $row->allowField(true)->save($params);
                Db::commit();
            }
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage() . $ids);
        }

        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    public function rollback($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row['stutas'] != 0) {
            $this->error('该订单已经完成！');
        }

        Db::startTrans();
        try {
            $agent = null;
            $row['stutas'] = -1;
            $row->save();
            $server = \app\admin\model\shopro\lucky\Server::get($row['lucky_id']);
            $money = bcmul($server['price'], $row['number'], 2);
            if (WalletService::changeNoEx($row['user_id'], 'money', $money, 'lucky_pay_back')) {
                (new Order())->where('lucky_user_id', $row['id'])->delete();
                $server->setDec('alr_number', $row['number']);
                $agent = new AgentService($row['user_id']);
                $user = \app\admin\model\User::get($row['user_id']);
                $orderAgent = new \addons\shopro\service\commission\Agent($user->parent_user_id);
                if ($orderAgent->isAgentAvaliable()) {
                    $orderAgent->agent->setDec('today_driect_money', $money);
                }
            } else {
                Db::rollback();
                $this->error('撤回失败！');
            }
            Db::commit();
            // 分销商数据统计&升级(异步执行)
//            if($agent){
//                $agent->createAsyncAgentUpgrade();
//            }
            $this->success();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

    }

}
